package io.renren.modules.psorder.controller;

import com.google.common.collect.Lists;
import io.renren.common.utils.*;
import io.renren.common.utils.excel.ExportExcel;
import io.renren.modules.api.annotation.AuthIgnore;
import io.renren.modules.psorder.entity.PsOrderEntity;
import io.renren.modules.psorder.service.PsOrderService;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 配送订单表
 *
 * @author wangdajiang
 * @email 2750757088@qq.com
 * @date 2017-12-02 17:22:15
 */
@RestController
@RequestMapping("/psorder")
public class PsOrderController {
    @Autowired
    private PsOrderService psOrderService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("psorder:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<PsOrderEntity> psOrderList = psOrderService.queryList(query);
        int total = psOrderService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(psOrderList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("psorder:info")
    public R info(@PathVariable("id") Long id) {
        PsOrderEntity psOrder = psOrderService.queryObject(id);

        return R.ok().put("psOrder", psOrder);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("psorder:save")
    public R save(@RequestBody PsOrderEntity psOrder) {
        psOrderService.save(psOrder);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("psorder:update")
    public R update(@RequestBody PsOrderEntity psOrder) {
        psOrderService.update(psOrder);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("psorder:delete")
    public R delete(@RequestBody Long[] ids) {
        psOrderService.deleteBatch(ids);

        return R.ok();
    }


    @RequestMapping("/listss")
    public R listss(String orderNum) {
        //查询列表数据
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(orderNum);
        return R.ok().put("psOrder", psOrder);
    }


    //创建Excel
    @AuthIgnore
    @RequestMapping(value= "/createExcel",method  = RequestMethod.GET)
    public String createExcel(HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> params) throws IOException {
        List<PsOrderEntity> psOrderList = psOrderService.queryListExcel(params);
        //创建HSSFWorkbook对象(excel的文档对象)
        XSSFWorkbook wb = new XSSFWorkbook();
        //建立新的sheet对象（excel的表单）
        XSSFSheet sheet = wb.createSheet("司机账务表");
        //在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
        XSSFRow row1 = sheet.createRow(0);
        //创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
        XSSFCell cell = row1.createCell(0);
        //设置单元格内容
        cell.setCellValue("司机订单详情一览表");
        //合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
        //在sheet里创建第二行
        XSSFRow row2 = sheet.createRow(1);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("司机姓名");
        row2.createCell(1).setCellValue("司机电话");
        row2.createCell(2).setCellValue("完成订单时间");
        row2.createCell(3).setCellValue("起点名称");
        row2.createCell(4).setCellValue("终点名称");
        row2.createCell(5).setCellValue("实际行驶距离");
        row2.createCell(6).setCellValue("订单状态");
        row2.createCell(7).setCellValue("订单金额");
        row2.createCell(8).setCellValue("支付方式");
        row2.createCell(9).setCellValue("支付时间");
        row2.createCell(10).setCellValue("实际支付金额");
        row2.createCell(11).setCellValue("额外费用");
        row2.createCell(12).setCellValue("支付状态");
        //在sheet里创建第三行

        for(int i= 0; i < psOrderList.size(); i++){
            PsOrderEntity psOrder = psOrderList.get(i);
            XSSFRow row = sheet.createRow(i+2);

            row.createCell(i).setCellValue(psOrder.getDriverName());
            row.createCell(i+1).setCellValue(psOrder.getDriverTel());
            row.createCell(i+2).setCellValue(psOrder.getCompleteTime() == null ? "" : psOrder.getCompleteTime().toString());
            row.createCell(i+3).setCellValue(psOrder.getStartName());
            row.createCell(i+4).setCellValue(psOrder.getEndName());
            row.createCell(i+5).setCellValue(psOrder.getRealdistance());
            row.createCell(i+6).setCellValue(psOrder.getOrderStatus());
            row.createCell(i+7).setCellValue(psOrder.getOrderMoney()== null ? "" :psOrder.getOrderMoney().toString());
            row.createCell(i+8).setCellValue(psOrder.getPayType());
            row.createCell(i+9).setCellValue(psOrder.getPayTime() == null ? "" : psOrder.getPayTime().toString());
            row.createCell(i+10).setCellValue(psOrder.getPayRealymoney() == null ? "":psOrder.getPayRealymoney().toString());
            row.createCell(i+11).setCellValue(psOrder.getExtraCharge() == null ? "":psOrder.getExtraCharge().toString());
            String status = "";
            if(psOrder.getPayStatus().equals("0")){
                status = "未支付";
            }else if(psOrder.getPayStatus().equals("1")){
                status = "已支付";
            }else{
                status = "";
            }
            row.createCell(i+12).setCellValue(status);
        }
        //输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=details.xls");
        response.setHeader("Content-disposition", "attachment; filename="+ ChangeChina.toUtf8String("司机订单详情.xls"));
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
        return null;
    }

	/**
	 * 导出excel文件
	 */
//	@RequiresPermissions("empinfomodify:list")
	@AuthIgnore
	@RequestMapping(value = "/list/export", method = RequestMethod.GET)
	public String exportFile(HttpServletRequest request, HttpServletResponse response) {
		try {
			String op =request.getParameter("op");
			List<PsOrderEntity> list =null;
			if("export".equals(op)){//导出数据
				Map<String, Object> params = new HashMap<>();
				list = psOrderService.queryList(params);
			}else if("download".equals(op)){//下载模板
				list = Lists.newArrayList();

			}
			String fileName =  ChangeChina.toUtf8String("司机-订单详情展示") + DateUtils.format(new Date(),"yyyyMMddHHmmss") + ".xlsx";
			new ExportExcel("司机-订单详情展示", PsOrderEntity.class).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			//throw new RRException("导出求职者信息管理记录失败！失败信息：" + e.getMessage());
		}
		return null;
//		return "redirect:empinfomodify/list";
	}



}
